/*
 * @Author: DaTree
 * @Date: 2020-11-16 10:43:25
 * @LastEditTime: 2021-06-02 15:22:21
 * @LastEditors: DaTree
 * @Description: DaTreeEdit
 * @FilePath: \services\src\controller\index.js
 * @天将降大任于是人也，必先苦其心志，劳其筋骨，饿其体肤，空乏其身，行拂乱其所为。 ——《孟子•告子下》
 * @symbol_custom_string_obkoro1_copyright: Copyright ${now_year} DaTree
 */
import chalk from 'chalk' // 紫色字体
import config from '../config/index'
const port = config.apiPort

console.log(chalk.magentaBright(`\n Starting api Server On Port ${port}...`))
import express from 'express' // 引入express模块
import path from 'path'
import fs from 'fs'

import SocketHub from './socket/socket-hub'
const app = express() // 实例化express

// var app = express();
var server = require('http').Server(app);

new SocketHub(server)

const readDir = (entry) => {
  let filePaths = []
  const dirInfo = fs.readdirSync(entry)
  dirInfo.forEach((item) => {
    const location = path.join(entry, item)
    const info = fs.statSync(location)
    if (info.isDirectory()) {
      // eslint-disable-next-line no-unused-vars
      filePaths = filePaths.concat(readDir(location))
    } else {
      filePaths.push(location)
    }
  })
  return filePaths
}

let router = require('./routers')

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE")
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  )
  // 利用闭包的特性获取最新的router对象，避免app.use缓存router对象
  router(req, res, next)
})

import chokidar from 'chokidar' // 文件监听器

const mockDir = path.join(process.cwd(), '')

function cleanCache (modulePath) {
  let module = require.cache[modulePath]
  try {
    // remove reference in module.parent
    if (module.parent) {
      module.parent.children.splice(module.parent.children.indexOf(module), 1)
    }
    delete require.cache[modulePath]
  } catch (e) {
    console.log(e)
  }
}

// 开启文件监听（热重启）
chokidar
  .watch(mockDir, {
    // ignored: /mock-server/,
    ignoreInitial: true,
  })
  .on('all', (event, filePath) => {
    if (event === 'change' || event === 'add') {
      try {
        cleanCache(require.resolve('./routers'))
        const moduleDir = path.join(process.cwd(), 'src/controller/modules')
        let modulePaths = readDir(moduleDir)
        modulePaths = modulePaths.concat(readDir(path.join(process.cwd(), 'src/controller/socket')))
        modulePaths.forEach((p) => {
          try {
            cleanCache(p)
          } catch (error) {

          }

        })

        try {
          router = require('./routers')
          console.log(
            chalk.magentaBright(
              `\n Api Server Hot Reload Success! Changed  ${filePath}`
            )
          )
        } catch (ex) {
          console.error(
            chalk.magentaBright(
              `\n Api Server Hot Reload Module Update Failed`
            )
          )
          console.error(chalk.magentaBright(`\n Api Server Error Info:`))
          console.log(ex)
        }
      } catch (error) {
        console.log(chalk.redBright(error))
      }
    }
  })

server.listen(port)
console.log(chalk.magentaBright(`\n Api Server Is Running On ${port}.`))